package com.sh.handler;

import android.content.Context;
import android.util.Log;
import com.google.gson.Gson;
import com.qiniu.android.utils.StringUtils;
import com.sh.Application.BaseApplication;
import com.sh.struts.LoginInfo;
import com.sh.utils.CommonStringUtils;
import com.sh.utils.SPUtils;
import com.sh.utils.UserManagerUtils;

import java.util.HashMap;
import java.util.Map;

import static com.sh.struts.GlobalDefine.SP_USER_COUNT_MAX;


public class LoginHandler {
    /**
     * 登录处理器
     *
     * @param username
     * @param password
     * @return
     */
    public static Map<String, String> userLogin(String username, String password) {
        Context context = BaseApplication.getInstance();
        Map<String, String> loginInfo = UserManagerUtils.userLoginVerify(username, password);
        Log.i("login: ", loginInfo.toString());
        Map<String, String> resMap = new HashMap<>();
        if ("success".equals(loginInfo.get("status"))) {
            resMap.put("status", "success");
            Map<String, String> map = new HashMap<>();
            map.put("username", username);
            map.put("password", password);
            String key = containAndReplace(map, context);
            SPUtils.put(context, "cur_user", key);
            SPUtils.put(context, "is_login", true);
            LoginInfo info = new LoginInfo();
            info.setUserId(CommonStringUtils.safeInteger(loginInfo.get("user_id")));
            info.setUserImgUrl(loginInfo.get("user_img"));
            info.setUsername(loginInfo.get("username"));
            BaseApplication.setLoginInfo(info);
        } else {
            BaseApplication.setLoginInfo(null);
            resMap.put("status", "failure");
            resMap.put("msg", loginInfo.get("msg"));
        }
        return resMap;
    }

    /**
     * 判断当前登录的用户信息是否存在于SharedPreferences里，不存在则添加进去，存在则替换
     *
     * @param map
     */
    public static String containAndReplace(Map<String, String> map, Context context) {
        Integer count = (Integer) SPUtils.get(context, "user_count", 0);
        String resKey = null;
        for (int i = 1; i <= count; i++) {
            String key = String.format("user_%s", i);
            String userJson = (String) SPUtils.get(context, key, "{}");
            Map<String, String> tempMap = new Gson().fromJson(userJson, Map.class);
            if (map.get("username").equals(tempMap.get("username"))) {
                SPUtils.put(context, key, new Gson().toJson(map));
                resKey = key;
                return resKey;
            }
        }
        if (count == SP_USER_COUNT_MAX) {
            resKey = String.format("user_%s", SP_USER_COUNT_MAX);
        } else {
            resKey = String.format("user_%s", count + 1);
            count += 1;
        }
        SPUtils.put(context, resKey, new Gson().toJson(map));
        SPUtils.put(context, "user_count", count);
        //Log.i("put result", (String) SPUtils.get(context,resKey,"GGGG"));
        return resKey;
    }

    /**
     * 自动登陆，在SP找到上次登陆的用户，登陆，没有的话就不登陆
     */
    public static Map<String,String> autoLogin() {
        String key = (String) SPUtils.get(BaseApplication.getInstance(),"cur_user","no key");
        String lastLoginInfo = (String) SPUtils.get(BaseApplication.getInstance(),key,"{}");
//        Log.i("lastLoginInfo ",CommonStringUtils.safeString(lastLoginInfo));
        Map<String,String> map = new HashMap<>();
        if(lastLoginInfo != null) {
            try {
                map = new Gson().fromJson(lastLoginInfo, Map.class);
            }catch (Exception e){
                Log.e("ParseJsonError: ",e.getMessage());
            }
        }
        String username = map.containsKey("username") ? map.get("username") : "";
        String password = map.containsKey("password") ? map.get("password") : "";
        Map<String,String> resMap;
        if(!StringUtils.isNullOrEmpty(username) && !StringUtils.isNullOrEmpty(password)){
            resMap = userLogin(username,password);
        }else{
            resMap = new HashMap<>();
            resMap.put("status","failure");
            SPUtils.put(BaseApplication.getInstance(),"is_login",false);
        }
        return resMap;
    }

    /**
     * 退出登录状态
     *
     * @return 操作成功与否
     */
    public static boolean logout() {
        Context context = BaseApplication.getInstance();
        try {
            BaseApplication.setLoginInfo(null);
            SPUtils.put(context, "is_login", false);
            SPUtils.remove(context, "cur_user");
        } catch (Exception e) {
            Log.e(e.getClass().getName(), e.getMessage());
            return false;
        }
        return true;
    }
}
